<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { ActiveHealthCheckConfig, HealthCheckConfig, PassiveHealthCheckConfig } from '../../services/client';
import NtmPassiveHealthCheckConfigEditor from './NtmPassiveHealthCheckConfigEditor.vue';
import NtmActiveHealthCheckConfigEditor from './NtmActiveHealthCheckConfigEditor.vue';

const props = defineProps<{ propNamePrefix?: string }>()
const model = defineModel<HealthCheckConfig>({ default: new HealthCheckConfig() })
const modelValue = reactive(model.value);
watch(modelValue, (value) => {
    model.value = value;
})

const computedPropName = (propName: string) => {
    return computed(() => {
        if (props.propNamePrefix) {
            return `${props.propNamePrefix}.${propName}}`
        }
        else {
            return propName;
        }
    })
}

const passivePropName = computedPropName('passive')
const activePropName = computedPropName('active')
const availableDestinationsPolicyPropName = computedPropName('availableDestinationsPolicy')

const initPassiveHealthConfig = () => {
    modelValue.passive = new PassiveHealthCheckConfig();
}

const initActiveHealthConfig = () => {
    modelValue.active = new ActiveHealthCheckConfig();
}

const removePassiveHealthConfig = () => {
    modelValue.passive = undefined;
}

const removeActiveHealtnConfig = () => {
    modelValue.active = undefined;
}
</script>

<template>
    <ElFormItem>
        <ElSpace>
            <ElButton v-if="!modelValue.passive" @click="initPassiveHealthConfig">Add Passive Health Config</ElButton>
            <ElButton v-if="!modelValue.active" @click="initActiveHealthConfig">Add Active Health Config</ElButton>
        </ElSpace>
    </ElFormItem>

    <ElFormItem :prop="passivePropName" v-if="modelValue.passive">
        <template #label>
            <ElSpace>
                <span>Passive</span>
                <ElButton size="small" type="danger" @click="removePassiveHealthConfig">移除</ElButton>
            </ElSpace>
        </template>
        <NtmPassiveHealthCheckConfigEditor v-model="modelValue.passive"></NtmPassiveHealthCheckConfigEditor>
    </ElFormItem>
    <ElFormItem :prop="activePropName" v-if="modelValue.active">
        <template #label>
            <ElSpace>
                <span>Active</span>
                <ElButton size="small" type="danger" @click="removeActiveHealtnConfig">移除</ElButton>
            </ElSpace>
        </template>
        <NtmActiveHealthCheckConfigEditor v-model="modelValue.active"></NtmActiveHealthCheckConfigEditor>
    </ElFormItem>
    <ElFormItem label="Available Destinations Policy" :prop="availableDestinationsPolicyPropName">
        <ElInput v-model="modelValue.availableDestinationsPolicy"></ElInput>
    </ElFormItem>
</template>